﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Domain;
using Cms.Domain.Wrappers;
using Cms.Web.Framework.Controls;

namespace Cms.Web.UI.Admin
{
    public partial class Plugins : AdminPage, IPluginsView
    {
        private PluginsPresenter _presenter;


        public override string HelpPage
        {
            get { return "dialogs/plugins.aspx"; }
        }

        #region IPluginsView Members

        public void SetPlugins(IList<PluginDescription> plugins)
        {
            rpPlugins.DataSource = plugins;
            rpPlugins.DataBind();
        }


        public string ContextTranslationFile
        {
            get { return "Admin/Translations/Plugins.xml"; }
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            _presenter = new PluginsPresenter(this);
            HeadingText = GetText(this, "Heading");
            if (!Page.IsPostBack)
            {
                _presenter.Initialize();
                HeadingIcon = litIcon.Text;
            }
        }


        protected void rpPlugins_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem)
                return;
            var pluginDescription = (PluginDescription) e.Item.DataItem;
            var litID = (Literal) e.Item.FindControl("litID");
            var litName = (Literal) e.Item.FindControl("litName");
            var litDescription = (Literal) e.Item.FindControl("litDescription");
            var litTemplatable = (Literal) e.Item.FindControl("litTemplatable");
            var litTemplates = (Literal) e.Item.FindControl("litTemplates");

            litID.Text = "<span id=\"";
            litID.Text += pluginDescription.Plugin is TemplatablePlugin ? "T" : "P";
            litID.Text += pluginDescription.Plugin.ID + "\">";
            litName.Text = pluginDescription.Name;
            litDescription.Text = pluginDescription.Description;
            litTemplatable.Text = pluginDescription.Templatable ? GetText(this, "Yes") : GetText(this, "No");
            if (!pluginDescription.Templatable)
                return;
            foreach (PluginTemplate template in _presenter.GetTemplates((pluginDescription.Plugin as TemplatablePlugin)))
            {
                if (litTemplates.Text != "")
                    litTemplates.Text += ", ";
                litTemplates.Text += template.Name;
            }
        }
    }
}